﻿#include "base.h"
#include "stddef.h"
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "assert.h"
#include "common.h"

#define AS_DOUBLE

static char g_ref_string[4096];

void init_string_ref(string_ref_t* ref, const char* buffer)
{
    assert(ref);
    ref->base = buffer;
    ref->offset = 0;
    ref->size = 0;
}

// simple
char* ref_to_string(const string_ref_t* ref)
{
    assert(ref && ref->size + 1 <= sizeof(g_ref_string));
    assert(ref->base);
    memcpy(g_ref_string, ref->base + ref->offset, ref->size);
    g_ref_string[ref->size] = 0;
    return g_ref_string;
}

bool ref_to_string_is_full(const string_ref_t* ref)
{
    return ref->size >= (int)sizeof(g_ref_string) - 1;
}

// safe
char* ref_to_mstring(const string_ref_t* ref)
{
    assert(ref->base);
    char* ptr = malloc(ref->size + 1);
    assert(ptr);
    memcpy(ptr, ref->base + ref->offset, ref->size);
    ptr[ref->size] = 0;
    return ptr;
}

char ref_char(const string_ref_t* ref, int index)
{
    assert(ref && ref->base);
    if (index <= ref->size)
        return ref->base[ref->offset];
    else
        return '\0';
}

void* memdup(void* src, size_t size)
{
    void* ret = malloc(size);
    memcpy(ret, src, size);
    return ret;
}
